package com.dhcc.sds.standard.controller;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.standard.entity.SdsStandSourceEntity;
import com.dhcc.sds.standard.service.ISdsStandSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.base.warpper.EmptyWarpper;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.page.PageFactory;
import com.dhcc.core.framework.util.CommonUtil;



import com.dhcc.sds.standard.entity.SdsStandSourceFieldEntity;
import com.dhcc.sds.standard.service.ISdsStandSourceFieldService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 数据源输出内容
 * 
 * @ClassName: SdsStandSourceFieldController
 * @Description: TODO
 * @author sunyingjie
 * @date 2021-03-22 10:09:52
 */
@Controller
@RequestMapping("${sys.backendPath}/sds/sdsstandsourcefield")
public class SdsStandSourceFieldController extends BaseController {

	private String PREFIX = "/backend/sds/sdsstandsourcefield/";

	@Autowired
	private ISdsStandSourceFieldService sdsStandSourceFieldService;

    @Autowired
    private ISdsStandSourceService sdsStandSourceService;
	

    /**
     * 跳转到数据源输出内容列表首页
     */
    @RequestMapping("")
    public String index(Model model) {
        model.addAttribute("sourceMap",sdsStandSourceService.getSourceMap());
        return PREFIX + "sdsstandsourcefield.html";
    }
	
    /**
     * 跳转到新增数据源输出内容
     */
    @RequestMapping("/to_add")
    public String toAdd(Model model) {
        model.addAttribute("sourceMap",sdsStandSourceService.getSourceMap());
        return PREFIX + "sdsstandsourcefield_add.html";
    }
	
	/**
     * 跳转到修改数据源输出内容
     */
    @RequestMapping("/to_update/{sdsStandSourceFieldId}")
    public String toUpdate(@PathVariable Long sdsStandSourceFieldId, Model model) {
        SdsStandSourceFieldEntity sdsStandSourceField = this.sdsStandSourceFieldService.selectById(sdsStandSourceFieldId);
        model.addAttribute("sdsStandSourceField",sdsStandSourceField);
        model.addAttribute("sourceMap",sdsStandSourceService.getSourceMap());
        return PREFIX + "sdsstandsourcefield_edit.html";
    }

    /**
     * 获取数据源输出内容列表
     */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam Map<String, Object> params) {
		Page<SdsStandSourceFieldEntity> page = new PageFactory<SdsStandSourceFieldEntity>().defaultPage();
        List<SdsStandSourceFieldEntity> result = this.sdsStandSourceFieldService.page(page,params);
        page.setRecords((List<SdsStandSourceFieldEntity>) new EmptyWarpper(result).warp());

        return R.packForBT(page);
    }

    /**
     * 新增数据源输出内容
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(SdsStandSourceFieldEntity sdsStandSourceField) {
        if (CommonUtil.isOneEmpty(sdsStandSourceField)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        sdsStandSourceField.insert();
        return R.ok();
    }

    /**
     * 删除数据源输出内容
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long sdsStandSourceFieldId) {
	
        this.sdsStandSourceFieldService.deleteById(sdsStandSourceFieldId);

        return R.ok();
    }

    /**
     * 修改数据源输出内容
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(SdsStandSourceFieldEntity sdsStandSourceField) {
        if (CommonUtil.isOneEmpty(sdsStandSourceField)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        SdsStandSourceFieldEntity old = this.sdsStandSourceFieldService.selectById(sdsStandSourceField.getId());

        old.setSourceId(sdsStandSourceField.getSourceId());
        old.setFieldCode(sdsStandSourceField.getFieldCode());
        old.setFieldDesc(sdsStandSourceField.getFieldDesc());
        old.setIsActive(sdsStandSourceField.getIsActive());
        old.setResume(sdsStandSourceField.getResume());
        old.updateAllColumnById();
        return R.ok();
    }

    /**
     * 导出数据源输出内容
     */
    @RequestMapping("/export")
    public void export(@RequestParam(required = false) String sourceId,
                            HttpServletRequest request,
                            HttpServletResponse response) {

        Map params = new HashMap();
        params.put("sourceId", sourceId);
        List<SdsStandSourceFieldEntity> result = this.sdsStandSourceFieldService.list(params);
        SdsStandSourceEntity sourceEntity = sdsStandSourceService.selectById(sourceId);

        // 通过工具类创建writer，默认创建xls格式
        BigExcelWriter writer = (BigExcelWriter) ExcelUtil.getBigWriter();
        writer.renameSheet("数据源输出内容");
        // 一次性写出内容，使用默认样式
        if (CommonUtil.isNotEmpty(result)) {
            ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
            for (SdsStandSourceFieldEntity obj : result) {
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("数据源名称", sourceEntity.getSourceDesc());
                row.put("字段代码", obj.getFieldCode());
                row.put("字段名称", obj.getFieldDesc());
                row.put("备注说明", obj.getResume());
                row.put("是否有效", obj.getIsActive()!=0?"是":"否");
                rows.add(row);
            }
            writer.write(rows);
            writer.setColumnWidth(0, 20);
            writer.setColumnWidth(1, 20);
            writer.setColumnWidth(2, 20);
            writer.setColumnWidth(3, 30);
            writer.setColumnWidth(4, 15);
        } else {
            List<String> row = CollUtil.newArrayList("无数据");
            List<List<String>> rows = new ArrayList<List<String>>();
            rows.add(row);
            writer.write(rows);
        }

        ServletOutputStream out = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "数据源输出内容字典_" + sdf.format(new Date()) + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859_1"));
            out = response.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            writer.flush(out);
            // 关闭writer，释放内存
            writer.close();
        }
    }

    /**
     * 跳转到数据源输出内容的页面
     */
    @RequestMapping("/to_import")
    public String toImport() {
        return PREFIX + "import.html";
    }

    /**
     * 导入数据源输出内容字典
     */
    @RequestMapping(method = RequestMethod.POST, path = "/import")
    @ResponseBody
    public R impEntities(@RequestPart("file") MultipartFile file) {
        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> all = reader.read();
            this.sdsStandSourceFieldService.importEntities(all);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.ok();
    }
	
}
